import React, { useEffect, useState } from "react";
class Effect1 extends React.Component {
	constructor(props) {
		super(props);
		this.state = { count: 0 };
	}
	componentDidMount() {
		document.title = `你点击了 ${this.state.count} 次`;
	}
	componentDidUpdate() {
		document.title = `你点击了 ${this.state.count} 次`;
	}
	render() {
		return (
			<div>
				<h2>{this.state.count}</h2>
				<button
					onClick={() =>
						this.setState({
							count: this.state.count + 1,
						})
					}>
					click
				</button>
			</div>
		);
	}
}
function Effect2() {
	let [count, setCount] = useState(0);
	useEffect(() => {
		document.title = `你点击了 ${count} 次`;
	});
	return (
		<div>
			<h2>{count}</h2>
			<button onClick={() => setCount(count + 1)}>click</button>
		</div>
	);
}
function Effect3() {
	let [x, setX] = useState(0);
	let [y, setY] = useState(0);

	useEffect(() => {
		console.log("x effect", x);
	}, [x]);
	useEffect(() => {
		console.log("y effect", y);
	}, [y]);
	useEffect(() => {
		console.log("xy effect", x, y);
	}, [x, y]);
	console.log("render?");
	return (
		<div>
			<h2>
				{x} + {y} = {x + y}
			</h2>
			<label>
				x:
				<input
					defaultValue={x}
					onChange={(e) => {
						setX(+e.target.value);
					}}
				/>
			</label>
			<label>
				y:
				<input
					defaultValue={y}
					onChange={(e) => {
						setY(+e.target.value);
					}}
				/>
			</label>
		</div>
	);
}

function Effect4() {
	const [count, setCount] = useState(0);
	useEffect(() => {
		const timer = setTimeout(() => setCount(count + 1), 3000);
		return () => {
			clearTimeout(timer);
		};
	});
	return (
		<div>
			<h2>count={count}</h2>
			<button onClick={() => setCount((count) => count + 1)}>add</button>
		</div>
	);
}
export default function UseEffectDemo() {
	return (
		<div>
			<Effect1 />
			<Effect2 />

			<Effect3 />
			<Effect4 />
		</div>
	);
}
